package com.example.myapplication2

import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream


class LogWriter(private var logFile: File) {

    private var isCompressing = false

    fun writeLog(message: String) {
        synchronized(this) {
            FileWriter(logFile, true).use { writer ->
                writer.write("""$message""".trimIndent())

                // 添加logcat的日志信息
                try {
                    val process = Runtime.getRuntime().exec("logcat -d")
                    val reader = BufferedReader(InputStreamReader(process.inputStream))
                    var line: String?
                    while (reader.readLine().also { line = it } != null) {
                        writer.write(line)
                        writer.write("\n")
                    }
                    process.waitFor()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

                // 检查文件大小
                if (logFile.length() > MAX_SIZE) {
                    if (!isCompressing) {
                        isCompressing = true
                        Thread { compressLogFile() }.start()
                    }
                }
            }
        }
    }


    /***
     *
     *
     * */
    private fun compressLogFile() {
        synchronized(this) {
            try {
                val zipFile =
                    File(logFile.parent, logFile.name + ".zip")
                ZipOutputStream(FileOutputStream(zipFile)).use { zos ->
                    val zipEntry = ZipEntry(logFile.name)
                    zos.putNextEntry(zipEntry)
                    // ... 读写文件的代码
                    zos.closeEntry()
                }
                logFile.delete() // 删除原始文件
                logFile = File(logFile.parent, "newLogFile.log")
                isCompressing = false // 释放压缩标记
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    companion object {
        private const val MAX_SIZE = (10 * 1024 * 1024 // 10MB
                ).toLong()
    }
}
